package space.sakana.edusysback.util;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.lang.Nullable;

public class CookieUtil {

    @Nullable
    public static String getCookieValueByKey(String key, HttpServletRequest request){
        Cookie cookie = getCookieByKey(key, request);
        if (cookie==null){
            return null;
        }
        return cookie.getValue();
    }

    @Nullable
    public static Cookie getCookieByKey(String key, HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        if (cookies==null){
            return null;
        }
        for (Cookie cookie: cookies) {
            if (cookie.getName().equals(key)){
                return cookie;
            }
        }
        return null;
    }

    public static Cookie genCookie(String key, String value){
        Cookie cookie = new Cookie(key, value);
        cookie.setMaxAge(7*24*60*60);
        cookie.setPath("/");
        return cookie;
    }

}
